const fs = require('fs');
const path = require("path");
const DateTime = require('./datetime');

function getStackTrace() {
    let obj = {};
    Error.captureStackTrace(obj, getStackTrace);
    return obj.stack;
}

class Log {
    constructor(dirname="./log/"){
        this.dirname = dirname;
        this.flieType = 0;//0按天，1按小时
        this._mkdirs(dirname);
    }
    setType(type){
        this.flieType = type;
    }
    _mkdirs(dirname) {
        if (fs.existsSync(dirname)) {
            return true;
        } else {
            if (this._mkdirs(path.dirname(dirname))) {
                fs.mkdirSync(dirname);
                return true;
            }
        }
        return false;
    }
    _openfile() {
        let now = new DateTime();
        let fileName = "??";
        if (this.flieType==0) {
            fileName = now.date()+".log";
        } else {
            fileName = now.dateHour()+".log";
        }
        return [fileName, now.time()];
    }
    debug(str) {
        console.log(`[${DateTime.nowDatetime()}]${str}`);
    }
    print(str) {
        let name = this._openfile();
        let text = `[${name[1]}]${str}`;
        fs.writeFile(this.dirname+name[0], text+"\r\n", {flag:"a+"}, function(){});
        console.log(text);
    }
    file(str) {
        let name = this._openfile();
        let text = `[${name[1]}]${str}`;
        fs.writeFile(this.dirname+name[0], text+"\r\n", {flag:"a+"}, function(){});
    }
    error(str) {
        let name = this._openfile();
        let stack = null;
        if (typeof(str)!='string' && str.stack!=undefined) {
            stack = `[stack]${str.stack}`;
        } else {
            stack = `${str}[stack]${getStackTrace()}`;
        }
        let text = `[${name[1]}][err]${stack}`;
        fs.writeFile(this.dirname+name[0], text+"\r\n", {flag:"a+"}, function(){});
        console.log(text);
    }
    errorFile(str) {
        let name = this._openfile();
        let stack = null;
        if (str.stack) {
            stack = `[stack]${getStackTrace()}`;
        } else {
            stack = `${str}[stack]${getStackTrace()}`;
        }
        let text = `[${name[1]}][err]${stack}`;
        fs.writeFile(this.dirname+name[0], text+"\r\n", {flag:"a+"}, function(){});
    }
}

// let logtest = new Log();
// logtest.print("print 1");
// logtest.file("print 2");
// logtest.error("print 3");
// logtest.errorFile("print 4");
// logtest.debug("print 5");

module.exports = Log;